layui.define(['layer', 'form', 'table', 'api'], function (exports) {

    var $ = layui.$,
        form = layui.form,
        table = layui.table;
    api = layui.api;
    var layer = layui.layer;
    var parentForm = form;
    var parentLayer = layer;
    if (parent.layui) {
        parent.layui.use(["form", "layer"], function () {
            parentForm = parent.layui.form;
            parentLayer = parent.layui.layer;
            //初始化表单
            courier.initForm();
            courier.initUserVerify();
        })
    }
    let ROLES = {
        COURIER: {
            name: "快递员",
            color: "blue"
        },
        USER: {
            name: "普通用户",
            color: "gray"
        },
        ADMIN: {
            name: "管理员",
            color: "black"
        }
    };

    var courier = {
        init: function () {
            courier.initTable();
            courier.initSearch();
        },
        initTable: function () {
            //初始化表格
            table.render({
                elem: '#courierTable',
                url: layui.CONTEXT_PATH + '/backend/admin/user/list', //数据接口
                page: true, //开启分页
                autoSort: false,
                contentType: 'application/json;charset=utf-8',
                method: "POST",
                limits: [1, 10, 20, 50, 100, 200, 500],
                cols: [[ //表头
                    {field: 'username', title: '用户名', width: 150},
                    {field: 'name', title: '姓名', sort: true},
                    {field: 'phone', title: '手机号', width: 120},
                    {field: 'expressNum', title: '派件数'},
                    {field: 'loginTimes', title: '登录次数', sort: true},
                    {field: 'lastLoginTime', title: '最后一次登录时间', sort: true},
                    {field: 'lock', title: '状态'},
                    {
                        field: 'roles', title: '角色', templet: function (columnData) {
                            var roleEnNames = Array.from(columnData.roles.split(",")).map(item => {
                                return `<span class="layui-badge layui-bg-${ROLES[item].color}">${ROLES[item].name}</span>`;
                            });
                            return roleEnNames.join(" ");

                        }
                    },
                    {field: 'wealth', title: '操作', toolbar: '#listOptsBar'}
                ]],
                parseData: function (result) {
                    return {
                        code: result.code,
                        msg: result.msg,
                        count: result.data.count,
                        data: result.data.items
                    }
                }
            });
            //绑定表头排序事件
            table.on('sort(courierTable)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                table.reload('courierTable', {
                    initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                    where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        sort: {
                            fieldName: obj.field, //排序字段
                            order: obj.type //排序方式
                        }
                    }
                });
            });
            //监听工具条
            table.on('tool(courierTable)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                let event = obj.event;
                if (event === 'detail') {
                    courier.onDetail(obj);
                } else if (event === 'edit') {
                    courier.onEdit(obj)
                } else if (event === 'delete') {
                    courier.onDelete(obj)
                }
            });
        },
        initSearch: function () {
            form.on("submit(formSearch)", function (data) {
                table.reload('courierTable', {
                    where: {
                        search: {
                            name: data.field.name,
                            phone: data.field.phone
                        }
                    }
                });
                return false;
            })
        },
        initForm: function () {
            parentForm.on("submit(formCourierAdd)", function (data) {
                console.log(data);
                return false;
            });
        },
        initUserVerify: function () {
            parentForm.verify({
                //value：表单的值、item：表单的DOM对象
                "u-username": function (value, item) {
                    if (!/^\w+$/.test(value)) {
                        return '用户名不能有特殊字符';
                    }
                    if (/(^\_)|(\_+$)/.test(value)) {
                        return '用户名首尾不能出现下划线\'_\'';
                    }
                    if (/^\d+$/.test(value)) {
                        return '用户名不能全为数字';
                    }
                    var validateExists = courier.validateExists("username", value);
                    if (validateExists) {
                        return "用户名已存在";
                    }
                },
                "u-phone": function (value, item) {
                    var validateExists = courier.validateExists("phone", value);
                    if (validateExists) {
                        return "手机号已存在";
                    }
                },
                "u-idCard": function (value, item) {
                    var validateExists = courier.validateExists("idCard", value);
                    if (validateExists) {
                        return "身份证号已存在";
                    }
                },
                "u-password": function (value, item) {
                    if(value.length < 6 || value.length > 18){
                        return "密码必须在6~18位之间"
                    }
                    if (!/^(?![\d]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*()_+<>?:"|`;',./\\]+$)[\da-zA-Z~!@#$%^&*()_+<>?:"|`;',./\\]+$/.test(value)) {
                        return "字母、数字和特殊字符至少包含2种"
                    }
                    let formData = parentForm.val("formCourier");
                    if (formData.confirmPassword !== value) {
                        return "密码与确认密码不一致"
                    }

                },
                "u-confirmPassword": function (value, item) {
                    let formData = parentForm.val("formCourier");
                    if (formData.password !== value) {
                        return "密码与确认密码不一致"
                    }
                }

            });
        },
        onDetail: function (eventData) {
            parentLayer.open({
                type: 1,
                title: "添加快递员",
                area: ['700px', '500px'],
                fixed: false, //不固定
                content: $("#formWin").html()
            });
        },
        onDelete: function (eventData) {
            console.log("onDelete ", eventData);
        },
        onEdit: function (eventData) {
            console.log("onUpdate ", eventData);
        },
        validateExists: function (key, value) {
            var result = null;
            $.ajax({
                url: layui.CONTEXT_PATH + "/backend/admin/user/exists",
                data: {key, value},
                async: false,
                success: function (data) {
                    result = data.data;
                }

            })
            return result;
        }
    }
    exports("courier", courier);
});